<?php
namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use session;

class LoginController extends Controller
{
	//发起登录请求
    public function qqLogin()
    {
        //参数
        $url = "https://graph.qq.com/oauth2.0/authorize";
        $param['response_type'] = "code";
        $param['client_id']="101482622";
        $param['redirect_uri'] ="http://www.yuqingyong.cn/home/qqLoginNotify";
        $param['scope'] ="get_user_info";
        //-------生成唯一随机串防CSRF攻击
        $param['state'] = md5(uniqid(rand(), TRUE));
        session(['state_code'=>$param['state']]);
        //拼接url
        $param = http_build_query($param,"","&");
        $url = $url."?".$param;
        header("Location:".$url);
    }

	//QQ互联回调地址
	public function qqLoginNotify(Request $request)
	{
		$code = $request->input('code');
        $state = $request->input('state');
        if($code && $state == session('state_code')){
            //获取access_token
            $res = $this->getAccessToken($code,"101482622","989701c6a1ad6a3a8aef37500b55b384");
            parse_str($res,$data);
            $access_token = $data['access_token'];
            $url  = "https://graph.qq.com/oauth2.0/me?access_token=$access_token";
            $open_res = $this->httpsRequest($url);
            if(strpos($open_res,"callback") !== false){
                $lpos = strpos($open_res,"(");
                $rpos = strrpos($open_res,")");
                $open_res = substr($open_res,$lpos + 1 ,$rpos - $lpos - 1);
            }
            $user = json_decode($open_res);
            $open_id = $user->openid;
            $url = "https://graph.qq.com/user/get_user_info?access_token=$access_token&oauth_consumer_key=101482622&openid=$open_id";
            $user_info = $this->httpsRequest($url);
            //查询是否已经存在该openid
            $res = DB::table('users')->where('openid',$open_id)->select('type','status','uid','username')->first();
            if($res){
                //如果验证通过则更新用户的登录IP和时间
                $ta['updated_at'] = time();
                $ta['last_login_ip'] = get_real_ip();
                DB::table('users')->where('uid',$res->uid)->update($ta);
                //登录次数自增1
                DB::table('users')->where('uid',$res->uid)->increment('login_times');
            	session(['users'=>get_object_vars($res)]);
                return redirect('/');
            }else{
                $user_info = json_decode($user_info,true);
                $da['type'] = 2;
                $da['openid']   = $open_id;
                $da['username'] = $user_info['nickname'];
                $da['last_login_ip'] = get_real_ip();
                $da['password'] = md5('123456');
                $da['nickname'] = $user_info['nickname'];
                $da['head_img'] = $user_info['figureurl_qq_1'];
                $da['created_at'] = time();
                $uid   = DB::table('users')->insertGetId($da);
                $users = DB::table('users')->where('uid',$uid)->select('username','type','status','uid')->first();
                session(['users'=>get_object_vars($users)]);
                return redirect('/');
            }

        } else {
            # 授权失败
            return redirect('/prompt')->with(['message'=>'授权失败','url' =>'/', 'jumpTime'=>3,'status'=>'error']);
        }
	}

    // 登出
    public function loginOut(Request $request)
    {
        # 清除用户信息缓存
        $request->session()->forget('users');
        $request->session()->forget('state_code');
        return redirect('/');
    }


	//通过Authorization Code获取Access Token
    public function getAccessToken($code,$app_id,$app_key){
        $url="https://graph.qq.com/oauth2.0/token";
        $param['grant_type']="authorization_code";
        $param['client_id']=$app_id;
        $param['client_secret']=$app_key;
        $param['code']=$code;
        $param['redirect_uri']="http://www.yuqingyong.cn/home/qqLoginNotify";
        $param =http_build_query($param,"","&");
        $url=$url."?".$param;
        return $this->httpsRequest($url);
    }
    //httpsRequest
    public function httpsRequest($post_url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$post_url);//要访问的地址
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//执行结果是否被返回，0是返回，1是不返回
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);//设置超时
        $res = curl_exec($ch);//执行并获取数据
        return $res;
        curl_close($ch);
    }
}